package com.kkd.kkdapp.activity;

import java.text.DecimalFormat;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.kkd.kkdapp.Environment;
import com.kkd.kkdapp.R;
import com.kkd.kkdapp.base.BaseActivity;
import com.kkd.kkdapp.http.entity.ParticularsData;
import com.kkd.kkdapp.http.entity.Tags;
import com.kkd.kkdapp.http.manager.HttpCallBack;
import com.kkd.kkdapp.http.manager.KkdHttpMagager;
import com.kkd.kkdapp.utils.AppUtil;
import com.kkd.kkdapp.utils.LogUtil;
import com.kkd.kkdapp.utils.PreferenceUtils;
import com.kkd.kkdapp.view.CustomScrollView;
import com.kkd.kkdapp.view.CustomScrollView.OnRefreshListener;
import com.kkd.kkdapp.view.EditText.FinanceEditText;

/**
 * 
 * 信用宝详情
 * 
 * @author mty
 * 
 */
public class CreditParticularsActivity extends BaseActivity implements
		OnClickListener {

	private Button tender_bt; // 投标
	private RelativeLayout condition; // 投标状况
	private RelativeLayout project; // 项目描述
	private RelativeLayout measure; // 风险措施
	private RelativeLayout title_img; // 返回
	private CustomScrollView mScrollView; // 下拉刷新
	private TextView title; // 标题
	private TextView money_tv; // 投标金额
	private TextView residue; // 剩余金额
	private TextView earnings; // 利率
	private ProgressBar increase; // 利率进度
	private TextView percentage; // 进度值
	private Button counter_bt; // 计算器
	private String bidId; // 标ID
	private String toMidFlag = ""; // 标ID
	private TextView allotted; // 期限
	private TextView deficit; // 足额抵押
	private TextView interests; // 先息后本
	private TextView number; // 投标人数
	private String bidStatus; // 标的状态
	private int bidPeriod; // 理财期限
	private FinanceEditText calculate_ed;
	private TextView earning; // 产品预估收益
	private String riskMeasure;// 风险投资url
	private String ProjectDesc; // 项目描述url
	private String bidTitle; // 标的标题
	private int progress = 0;
	private double iinterest;
	private long bidAmount; // 招标金额
	private long totalLixi; // 总利息
	private TextView describe_tv; // 项目描述
	private RelativeLayout share; // 分享
	private Timer timer = null;
	private TimerTask mTimerTask = null;
	// private String version;
	private double balance;
	private TextView min_amount;
	private long lowestAmount;
	private long amountMultiple;
	private String bidPeriodType;
	private static final int DECIMAL_DIGITS = 2; // 输入框小数的位数
	private String bidInterest;
	private long bidFreeAmount;
	private String maxAmount;
	private RelativeLayout plan; // 还款计划
	private TextView planvice_tv; // 还款计划副标题
	private RelativeLayout course; // 项目历程
	private TextView coursevice_tv; // 项目历程副标题
	private String bidProgress;
	private String bidDescription;
	private double interest;
	private List<Tags> tags;
	private int poicount;
	private String particularsDesc;
	private Toast mToast;
	private String bidType;

	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case 1:

				setState(bidStatus);
				updateUI(bidTitle, bidAmount, bidFreeAmount, bidInterest,
						interest, tags, poicount);
				break;
			case 2:
				showToast(particularsDesc);
				break;
			case 3:
				String desc = (String) msg.obj;
				showToast(desc);
				break;
			case 4:
				mScrollView.onRefreshComplete();
				break;
			default:
				break;
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_credit_particulars);
		initView();
		setListener();
	}

	public void initView() {
		tender_bt = (Button) findViewById(R.id.tender_bt);
		condition = (RelativeLayout) this.findViewById(R.id.condition);
		project = (RelativeLayout) this.findViewById(R.id.project);
		measure = (RelativeLayout) this.findViewById(R.id.measure);
		title_img = (RelativeLayout) this.findViewById(R.id.title_img);
		mScrollView = (CustomScrollView) this.findViewById(R.id.pt_sv);
		title = (TextView) this.findViewById(R.id.title);
		money_tv = (TextView) this.findViewById(R.id.money_tv2);
		residue = (TextView) this.findViewById(R.id.residue);
		earnings = (TextView) this.findViewById(R.id.earnings);
		increase = (ProgressBar) this.findViewById(R.id.increase);
		percentage = (TextView) this.findViewById(R.id.percentage);
		counter_bt = (Button) findViewById(R.id.counter_bt);
		allotted = (TextView) this.findViewById(R.id.allotted);
		deficit = (TextView) this.findViewById(R.id.deficit);
		interests = (TextView) this.findViewById(R.id.interests);
		number = (TextView) this.findViewById(R.id.number);
		describe_tv = (TextView) this.findViewById(R.id.describe_tv);
		share = (RelativeLayout) this.findViewById(R.id.share);
		min_amount = (TextView) this.findViewById(R.id.min_amount);
		plan = (RelativeLayout) this.findViewById(R.id.plan);
		planvice_tv = (TextView) this.findViewById(R.id.planvice_tv);
		course = (RelativeLayout) this.findViewById(R.id.course);
		coursevice_tv = (TextView) this.findViewById(R.id.coursevice_tv);
		getMessage();

	}

	@Override
	protected void onStart() {
		super.onStart();
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (mTimerTask != null) {
			mTimerTask.cancel();
			mTimerTask = null;
		}
		if (timer != null) {
			timer.cancel();
			timer = null;
		}
		requestParticulars();
		mScrollView.onRefreshComplete();
		if (PreferenceUtils.getInstance().getLogin(this) == 0) {
			getAccountInfo();
		}
	}

	public void getMessage() {
		Intent intent = this.getIntent();
		bidId = intent.getStringExtra("bidId");
		toMidFlag = intent.getStringExtra("toMidFlag");
	}

	Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			if (progress != 0) {
				if (progress == 99) {
					increase.setProgress(100);
				} else {
					increase.setProgress(progress);
				}
			} else {
				increase.setProgress((int) iinterest);
			}
		};
	};

	public void setListener() {
		counter_bt.setOnClickListener(this);
		tender_bt.setOnClickListener(this);
		condition.setOnClickListener(this);
		project.setOnClickListener(this);
		measure.setOnClickListener(this);
		title_img.setOnClickListener(this);
		share.setOnClickListener(this);
		plan.setOnClickListener(this);
		course.setOnClickListener(this);
		mScrollView.setOnRefreshListener(new OnRefreshListener() {
			public void onRefresh() {

				if (mTimerTask != null) {
					mTimerTask.cancel();
					mTimerTask = null;
				}
				if (timer != null) {
					timer.cancel();
					timer = null;
				}
				requestParticulars();
			}
		});

	}

	@Override
	public void onClick(View v) {

		Intent intent;
		switch (v.getId()) {
		case R.id.tender_bt: // 投标
			if ("5002".equals(bidStatus)) {

				if (PreferenceUtils.getInstance().getLogin(this) == 0) { // 登陆验证

					if (PreferenceUtils.getInstance().getAutonym(this) == 1) { // 身份认证

						if (PreferenceUtils.getInstance().getBoundBankCard(
								CreditParticularsActivity.this) == 1) { // 判定银行卡是否绑定
							intent = new Intent(this,
									TenderAffirmActivity.class);
							intent.putExtra("bidId", bidId);
							intent.putExtra("bidTitle", bidTitle);
							intent.putExtra("bidPeriod", bidPeriod);
							intent.putExtra("amountMultiple", amountMultiple);
							intent.putExtra("lowestAmount", lowestAmount);
							intent.putExtra("bidPeriodType", bidPeriodType);
							intent.putExtra("bidInterest", bidInterest);
							intent.putExtra("bidFreeAmount", bidFreeAmount);
							intent.putExtra("maxAmount", maxAmount);
							intent.putExtra("bidAmount", bidAmount);
							intent.putExtra("totalLixi", totalLixi);
							intent.putExtra("bidType", bidType);
							intent.putExtra("toMidFlag", toMidFlag);
							intent.putExtra("toMidFlag", "3");
							intent.putExtra("businessType", "3");
							if ("501".equals(bidType)
									&& PreferenceUtils
											.getInstance()
											.getKkxfStatus(
													CreditParticularsActivity.this) == 0) {// 为体验标并且没有快快享福特权
								AppUtil.makeToastForCustomer(
										CreditParticularsActivity.this,
										PreferenceUtils
												.getInstance()
												.getKkxfExt(
														CreditParticularsActivity.this));
							} else {
								CreditParticularsActivity.this
										.startActivity(intent);
							}
						} else {
							if (balance == 0) {
								intent = new Intent(this,
										ForTenderActivity.class);
								LogUtil.e("bidPeriod", "" + bidPeriod);
								LogUtil.e("bidType", bidType);
								intent.putExtra("enterTypeFlag", 5);
								intent.putExtra("bidId", bidId);
								intent.putExtra("bidTitle", bidTitle);
								intent.putExtra("bidPeriod", bidPeriod);
								intent.putExtra("bidInterest", bidInterest);
								intent.putExtra("bidFreeAmount", bidFreeAmount);
								intent.putExtra("maxAmount", maxAmount);
								intent.putExtra("bidAmount", bidAmount);
								intent.putExtra("totalLixi", totalLixi);
								intent.putExtra("bidType", bidType);
								intent.putExtra("bidPeriodType", bidPeriodType);
								intent.putExtra("businessType", "3");
								intent.putExtra("toMidFlag", "3");
								startActivity(intent);
							} else {
								intent = new Intent(this,
										TenderAffirmActivity.class);
								intent.putExtra("bidType", bidType);
								intent.putExtra("bidId", bidId);
								intent.putExtra("bidTitle", bidTitle);
								intent.putExtra("bidPeriod", bidPeriod);
								intent.putExtra("amountMultiple",
										amountMultiple);
								intent.putExtra("lowestAmount", lowestAmount);
								intent.putExtra("bidPeriodType", bidPeriodType);
								intent.putExtra("bidInterest", bidInterest);
								intent.putExtra("bidFreeAmount", bidFreeAmount);
								intent.putExtra("maxAmount", maxAmount);
								intent.putExtra("bidAmount", bidAmount);
								intent.putExtra("totalLixi", totalLixi);
								intent.putExtra("toMidFlag", "3");
								intent.putExtra("businessType", "3");
								if ("501".equals(bidType)
										&& PreferenceUtils
												.getInstance()
												.getKkxfStatus(
														CreditParticularsActivity.this) == 0) {// 为体验标并且没有快快享福特权
									AppUtil.makeToastForCustomer(
											CreditParticularsActivity.this,
											PreferenceUtils
													.getInstance()
													.getKkxfExt(
															CreditParticularsActivity.this));
								} else {
									CreditParticularsActivity.this
											.startActivity(intent);
								}
							}

						}

					} else {
						intent = new Intent(this, ForTenderActivity.class);
						intent.putExtra("enterTypeFlag", 5);
						intent.putExtra("bidId", bidId);
						intent.putExtra("bidTitle", bidTitle);
						intent.putExtra("bidPeriod", bidPeriod);
						intent.putExtra("bidInterest", bidInterest);
						intent.putExtra("bidPeriodType", bidPeriodType);
						intent.putExtra("bidFreeAmount", bidFreeAmount);
						intent.putExtra("maxAmount", maxAmount);
						intent.putExtra("bidAmount", bidAmount);
						intent.putExtra("totalLixi", totalLixi);
						intent.putExtra("bidType", bidType);
						intent.putExtra("toMidFlag", "3");
						intent.putExtra("businessType", "3");
						LogUtil.e("bidPeriod", "" + bidPeriod);

						LogUtil.e("bidPeriodType", "" + bidPeriodType);
						this.startActivity(intent);
					}

				} else {
					intent = new Intent(this, LoginActivity.class);
					this.startActivity(intent);

				}
			}
			break;

		case R.id.condition: // 投标状况
			intent = new Intent(this, ConditionActivity.class);
			intent.putExtra("bidId", bidId);
			startActivity(intent);
			break;
		case R.id.project: // 项目描述
			if (!TextUtils.isEmpty(ProjectDesc)) {
				intent = new Intent(this, KKDWebActivity.class);
				intent.putExtra("url", ProjectDesc);
				intent.putExtra("shareUrl", "");
				intent.putExtra("titleName", "项目描述");
				startActivity(intent);
			}
			break;

		case R.id.measure: // 风险措施
			if (!"".equals(riskMeasure)) {
				intent = new Intent(this, KKDWebActivity.class);
				intent.putExtra("shareUrl", "");
				intent.putExtra("url", riskMeasure);
				intent.putExtra("titleName", "风险措施");
				startActivity(intent);
			}

			break;
		case R.id.title_img:
			finish();
			break;
		case R.id.counter_bt: // 计算器
			// if (AppUtil.isConnect(this)) {
			// DialogUtil.showCalculateWindow(this, v, bidPeriodType,
			// bidFreeAmount, bidAmount, totalLixi, bidPeriod);
			// }

			break;
		case R.id.share: // 分享
			String url = Environment.SHARE_ULR + "details.html?bidid=" + bidId;
			toShareURL(CreditParticularsActivity.this, url, "快快贷理财",
					"我正在使用快快贷进行理财,推将给你一个不错的标吧!拿好不用谢~",
					R.drawable.share_kkdai_logo);

			break;
		case R.id.plan: // 还款计划
			if (bidId != null) {
				intent = new Intent(this, RepaymentScheduleActivity.class);
				intent.putExtra("bidId", bidId);
				startActivity(intent);
			}
			break;
		case R.id.course: // 项目历程
			if (bidId != null) {
				intent = new Intent(this, KKDWebActivity.class);
				intent.putExtra("url", Environment.getH5Url()
						+ "itemPro.html?bidid=" + bidId);
				intent.putExtra("titleName", "项目历程");
				startActivity(intent);

			}
			break;
		}

	}

	protected void showToast() {
		if (mToast == null) {
			mToast = Toast.makeText(CreditParticularsActivity.this,
					R.string.investment_no, Toast.LENGTH_SHORT);
			mToast.setGravity(Gravity.CENTER, 0, 0);
		}
		mToast.show();

	}

	/**
	 * 
	 * 请求网络解析数据
	 */
	public void requestParticulars() {
		LogUtil.e("statusCode", bidId);

		KkdHttpMagager.getInstance().getParticularsManager(bidId,
				ParticularsData.class, new HttpCallBack() {

					@Override
					public void onSuccess(int statusCode, Object responseBody) {
						ParticularsData data = (ParticularsData) responseBody;
						bidId = data.getBidId();
						bidTitle = data.getBidTitle();
						bidAmount = data.getBidAmount();
						totalLixi = data.getTotalLixi();
						lowestAmount = data.getLowestAmount();
						amountMultiple = data.getAmountMultiple();
						bidPeriodType = data.getBidPeriodType();
						bidProgress = data.getBidProgress();
						bidFreeAmount = data.getBidFreeAmount();
						bidInterest = data.getInterestDisplay();
						interest = (1 - (double) bidFreeAmount / bidAmount);
						bidStatus = data.getBidStatus();
						bidPeriod = data.getBidPeriod();
						riskMeasure = data.getRiskMeasure();
						bidType = data.getBidType();
						ProjectDesc = data.getProjectDesc();
						maxAmount = data.getMaxAmountDisplay();
						tags = data.getTags();
						poicount = data.getPoiCount();
						bidDescription = data.getBidDescription();
						mHandler.sendEmptyMessage(1);

						mHandler.sendEmptyMessage(4);
					}

					@Override
					public void onFailure(int statusCode, String desc) {
						particularsDesc = desc;
						mHandler.sendEmptyMessage(2);
						mHandler.sendEmptyMessage(4);
					}
				});
	}

	public void setState(String bidStatus) {
		if ("5002".equals(bidStatus) || "5003".equals(bidStatus)) {
			plan.setClickable(false);
			planvice_tv.setText("暂无还款计划");
		} else if ("5005".equals(bidStatus)) {
			planvice_tv.setText("已还清");
		} else {
			planvice_tv.setText("还款中");
		}
		if ("5001".equals(bidStatus)) {
			tender_bt.setEnabled(false);
			coursevice_tv.setText("新建");
		} else if ("5002".equals(bidStatus)) {
			tender_bt.setEnabled(true);
			coursevice_tv.setText("投标");
		} else if ("5003".equals(bidStatus)) {
			tender_bt.setEnabled(false);
			coursevice_tv.setText("满标");
		} else if ("5004".equals(bidStatus)) {
			tender_bt.setEnabled(false);
			coursevice_tv.setText("还款中");
		} else if ("5005".equals(bidStatus)) {
			tender_bt.setEnabled(false);
			coursevice_tv.setText("已还清");
		} else if ("5006".equals(bidStatus)) {
			tender_bt.setEnabled(false);
			coursevice_tv.setText("待发布");
		} else if ("5007".equals(bidStatus)) {
			tender_bt.setEnabled(false);
			coursevice_tv.setText("处理中");
		} else if ("40011".equals(bidStatus)) {
			tender_bt.setEnabled(false);
			coursevice_tv.setText("已流标");
		}
	}

	public void updateUI(String bidTitle, long bidAmount, long bidFreeAmount,
			String bidInterest, double interest, List<Tags> tags, int poicount) {
		title.setText(bidTitle);
		DecimalFormat df = new DecimalFormat("0.00");
		String bmout = df.format(bidAmount * 0.01);
		money_tv.setText(bmout);
		String freeAmount = df.format(bidFreeAmount * 0.01);
		if (freeAmount.length() > 10) {
			residue.setTextSize(16f);
			min_amount.setTextSize(16f);
			earnings.setTextSize(16f);
		} else {
			residue.setTextSize(18f);
			min_amount.setTextSize(18f);
			earnings.setTextSize(18f);
		}
		residue.setText(freeAmount);
		LogUtil.e("freeAmount", "" + "9999999.00".length());
		String lowestAmount1 = df.format(lowestAmount * 0.01);
		earnings.setText(bidInterest);
		min_amount.setText("" + lowestAmount1);
		iinterest = (double) (interest * 100);
		if (timer != null) {
			timer.cancel();
			timer = null;
		}

		if (mTimerTask != null) {
			mTimerTask.cancel();
			mTimerTask = null;
		}

		if (timer == null)
			timer = new Timer();
		if (mTimerTask == null) {
			mTimerTask = new TimerTask() {

				@Override
				public void run() {
					progress = progress + 1;
					if (progress <= iinterest) {
						handler.sendEmptyMessage(1);
					} else {
						if (iinterest < 1 && iinterest > 0) {
							increase.setProgress(1);
						}
						progress = 0;
						mTimerTask.cancel();
						mTimerTask = null;
						timer.cancel();
						timer = null;
					}

				}
			};
		}
		timer.schedule(mTimerTask, 00, 10);
		String icon1_name = tags.get(0).getName();
		allotted.setText(icon1_name);
		String icon3_name = tags.get(1).getName();
		deficit.setText(icon3_name);
		String icon4_name = tags.get(2).getName();
		interests.setText(icon4_name);
		number.setText(poicount + "");

		percentage.setText(bidProgress + "%");
		if (TextUtils.isEmpty(bidDescription)) {
			describe_tv.setText("借款方信息、借款方地址、借款描述");
		} else {
			describe_tv.setText(bidDescription);
		}
	}

	/**
	 * 
	 * 查询账户余额
	 */
	public void getAccountInfo() {
		KkdHttpMagager.getInstance().getAccountInfoManager(String.class,
				new HttpCallBack() {

					@Override
					public void onSuccess(int statusCode, Object responseBody) {
						try {
							String responseString = responseBody.toString();
							JSONObject data = new JSONObject(responseString);
							balance = data.getDouble("balance");
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}

					@Override
					public void onFailure(int statusCode, String desc) {
						Message msg = new Message();
						msg.what = 3;
						msg.obj = desc;
						mHandler.sendMessage(msg);
					}
				});
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (mTimerTask != null) {
			mTimerTask.cancel();
			mTimerTask = null;
		}
		if (timer != null) {
			timer.cancel();
			timer = null;
		}

	}

}
